package org.smart4j.framework.bean;

import org.smart4j.framework.util.CastUtil;
import org.smart4j.framework.util.CollectionUtil;
import org.smart4j.framework.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求参数对象
 */
public class Param {

    private List<FormParam> formParamList;

    private List<FileParam> fileParamList;

    public Param(List<FormParam> formParamList) {
        this.formParamList = formParamList;
    }

    public Param(List<FormParam> formParamList, List<FileParam> fileParamList) {
        this.formParamList = formParamList;
        this.fileParamList = fileParamList;
    }

    public Map<String,Object> getFieldMap(){
        Map<String,Object> fieldMap= new HashMap<String,Object>();
        if(CollectionUtil.isNotEmpty(formParamList)){
            for(FormParam p:formParamList){
                String fieldName = p.getFieldName();
                Object fieldValue = p.getFieldValue();
                if(fieldMap.containsKey(fieldName)){
                    fieldValue = fieldMap.get(fieldName) + StringUtil.SEPARATOR + fieldValue;
                }
                fieldMap.put(fieldName,fieldValue);
            }
        }
        return fieldMap;
    }

    public Map<String,List<FileParam>> getFileMap(){
        Map<String,List<FileParam>> fileMap = new HashMap<>();
        if(CollectionUtil.isNotEmpty(fileParamList)){
            for(FileParam fileParam:fileParamList){
                String fieldName = fileParam.getFieldName();
                List<FileParam> fileParamList1;
                if(fileMap.containsKey(fieldName)){
                    fileParamList1 = fileMap.get(fieldName);
                }else{
                    fileParamList1 = new ArrayList<>();
                }
                fileParamList1.add(fileParam);
                fileMap.put(fieldName,fileParamList1);
            }
        }
    }

    public List<FileParam> getFileList(String fieldName){
        return getFileMap().get(fieldName);
    }

    public FileParam getFile(String fieldName){
        List<FileParam> fileParamList = getFileList(fieldName);
        if(CollectionUtil.isNotEmpty(fileParamList) && fileParamList.size()==1){
            return fileParamList.get(0);
        }
        return null;
    }



    //    private Map<String,Object> paramMap;
//
//    public Param(Map<String,Object> paramMap){
//        this.paramMap = paramMap;
//    }
//
//    public long getLong(String name){
//        return CastUtil.castLong(paramMap.get(name));
//    }
//
//    public Map<String, Object> getParamMap() {
//        return paramMap;
//    }
//
    public boolean isEmpty(){
        return CollectionUtil.isEmpty(fileParamList) && CollectionUtil.isEmpty(formParamList);
    }
}
